package permissions

import (
	"context"
	"database/sql"
	"errors"
	"product/authorization/model/permission"
	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"
	"product/common/datetime"
	"product/common/toolbox"
	"product/common/validator"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddPermissionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// add permissions
func NewAddPermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPermissionsLogic {
	return &AddPermissionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddPermissionsLogic) AddPermissions(req *types.AddPermissionReq) (resp *types.AddPermissionResp, err error) {
	ok, err := validInputPermissions(req)
	if !ok && err != nil {
		return &types.AddPermissionResp{
			Message: err.Error(),
			Ok:      false,
		}, nil
	}
	// 判断是否重复
	existsFlag := l.svcCtx.PermissionsModel.CheckNameExists(l.ctx, req.Name)
	if existsFlag {
		return &types.AddPermissionResp{
			Message: "权限已存在",
			Ok:      false,
		}, nil
	}
	// 判断权限值是否重复
	exists := l.svcCtx.PermissionsModel.CheckValueExists(l.ctx, int64(req.Value))
	if exists {
		return &types.AddPermissionResp{
			Message: "权限值已存在",
			Ok:      false,
		}, nil
	}
	entity := &permission.Permissions{
		PermissionName:  req.Name,
		PermissionValue: int64(req.Value),
		Description:     sql.NullString{String: req.Desc, Valid: !validator.IsEmptyString(req.Desc)},
		IsDeleted:       0,
		CreatedAt:       datetime.GetNowTimestamp(),
		UpdatedAt:       datetime.GetNowTimestamp(),
		ID:              toolbox.GetUniqueId(),
	}
	_, err = l.svcCtx.PermissionsModel.Insert(l.ctx, entity)
	if err != nil {
		return &types.AddPermissionResp{
			Message: "添加失败",
			Ok:      false,
		}, nil
	}
	return &types.AddPermissionResp{
		Message: "添加成功",
		Ok:      true,
	}, nil
}

func validInputPermissions(req *types.AddPermissionReq) (bool, error) {
	if validator.IsEmptyString(req.Name) {
		return false, errors.New("name不能为空")
	}
	if req.Value <= 0 {
		return false, errors.New("value不能为空")
	}
	return true, nil
}
